package com.tengroup.service;

import com.tengroup.entity.UserInfoEntity;
import com.tengroup.security.PasswordUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class PasswordResetService {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private StringRedisTemplate redisTemplate; // Redis 客户端

    @Autowired
    private UserService userService;  // 假设你有一个用户服务类来处理数据库操作

    // 发送验证码
    private String generateVerificationCode() {
        Random random = new Random();
        int code = 100000 + random.nextInt(900000);  // 生成一个6位数的验证码
        return String.valueOf(code);
    }

    // 发送验证码邮件
    // 发送验证码邮件
    // 在存储验证码时使用统一的键名格式
    public boolean sendVerificationCode(String toEmail) {
        try {
            String code = generateVerificationCode();  // 生成验证码
            // 使用统一格式存储验证码
            String redisKey = "reset_password:" + toEmail;
            redisTemplate.opsForValue().set(redisKey, code, 5, TimeUnit.MINUTES);
            System.out.println("Storing to Redis with key: " + redisKey);
            // 打印存储到 Redis 的验证码值
            System.out.println("Stored code in Redis for " + toEmail + ": " + code);

            String subject = "密码重置验证码";
            String text = "您的验证码是：" + code + "，有效期为5分钟。";
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom("2482970191@qq.com");   // 发件人邮箱
            helper.setTo(toEmail);                 // 收件人邮箱
            helper.setSubject(subject);            // 邮件主题
            helper.setText(text);                  // 邮件内容
            // 发送邮件
            mailSender.send(message);
            return true;
        } catch (MailException | MessagingException e) {
            e.printStackTrace();
            return false;
        }
    }



    // 验证验证码
    public boolean validateVerificationCode(String toEmail, String code) {
        // 使用统一格式的键来从 Redis 获取验证码
        String redisKey = "reset_password:" + toEmail;
        System.out.println("String to Redis with key: " + redisKey);
        String storedCode = redisTemplate.opsForValue().get(redisKey);
        System.out.println("Stored code from Redis: " + storedCode);

        // 验证验证码是否存在并且匹配
        return storedCode != null && storedCode.equals(code);  // 验证失败
    }



    // 更新密码
    public boolean updatePassword(String email, String newPassword) throws NoSuchAlgorithmException {
        UserInfoEntity user = userService.findByEmail(email);
        System.out.println(user);// 根据邮箱查找用户
        if (user != null) {
            // 生成盐值
            String salt = PasswordUtils.generateSalt();
            // 使用盐值加密密码
            String hashedPassword = PasswordUtils.hashPassword(newPassword, salt);

            user.setUserPassword(hashedPassword);  // 更新密码
            user.setSalt(salt);  // 保存盐值
            return userService.updateUser(user); // 保存更新后的用户信息
        }
        return false;
    }

    // 处理忘记密码的流程
    public boolean resetPassword(String email, String code, String newPassword) throws NoSuchAlgorithmException {
        if (validateVerificationCode(email, code)) {
            System.out.println(updatePassword(email, newPassword));
            return updatePassword(email, newPassword);
        } else {
            return false;
        }
    }
}
